﻿ 
using SHKF.B2C.Model.Entity.Sale;
using SqlSugar;
using System; 

namespace SHKF.B2C.BLL.LM
{
    public class IDBLL : LMBLL
    { 

        public IDBLL(SqlSugarClient db):base(db)
        {
            
        }

        public SaleID GetIDForSP(int WorkingType, string KeyWord, int CompanySN, int ShopSN)
        { 
            string id = "";
            int NewID = 0;

            try
            {
                this.db.BeginTran();

                string tag = "";
                if (WorkingType == 5)
                {
                    tag = "WS";
                }

                string strNow = DateTime.Now.ToString("yyyy-MM-dd");
                bool bExist = this.db.Queryable<IDNumberEnity>()
                    .Where(oo => oo.CompanySN == CompanySN
                && oo.ShopSN == ShopSN
                && oo.pDate == strNow)
                    .Any();

                if (bExist)
                {
                    IDNumberEnity iDNumber = this.db
                        .Queryable<IDNumberEnity>()
                        .Where(oo => oo.CompanySN == CompanySN
                    && oo.ShopSN == ShopSN
                    && oo.pDate == strNow).First();
                    NewID = iDNumber.ID + 1;

                    iDNumber.ID = NewID;
                    int result = this.db.Updateable<IDNumberEnity>(iDNumber)
                        .ExecuteCommand();
                }
                else
                {
                    NewID = 1;

                    IDNumberEnity iDNumber = new IDNumberEnity();
                    iDNumber.ID = NewID;
                    iDNumber.CompanySN = CompanySN;
                    iDNumber.ShopSN = ShopSN;
                    iDNumber.KeyWord = KeyWord;
                    iDNumber.pDate = strNow;
                    long SN = this.db.Insertable<IDNumberEnity>(iDNumber)
                       .ExecuteReturnBigIdentity();
                }

                id = tag + strNow.Replace("-", "") + NewID.ToString().PadLeft(4, '0');
                 
                this.db.CommitTran();

            }
            catch (Exception ex)
            {
                this.db.RollbackTran(); 
                throw ex;
            }
             
            return new SaleID() { ID = id, Num = NewID };
        }

        /// <summary>
        /// 销售单号
        /// </summary>
        /// <param name="CompanySN"></param>
        /// <param name="ShopSN"></param>
        /// <returns></returns>
        public SaleID GetSaleID(int CompanySN, int ShopSN)
        {
            return GetIDForSP(5, "SM_TSaleContent", CompanySN, ShopSN);
            
        }
    }
}
